'use strict';
const Service = require('egg').Service;
const dayjs = require('dayjs');



class ChatService extends Service {

  async getLatestMessage({ chatRoomId, fromUserId}) {
    const ctx = this.ctx;

    const query = { from_user_id: fromUserId, chat_room_id: chatRoomId };

    const option = {
      skip: 0,
      limit: 1,
      sort: '-create_at',
    };

    const resultMessageData = await ctx.model.ChatMessage.find(query, [], option).exec();

    if (resultMessageData && resultMessageData.length) {
      return [ resultMessageData[0] ];
    }

    return [ null ];
  }

  getChatRoomCountByQuery(query) {
    return this.ctx.model.ChatRoom.count(query).exec();
  }

  async getChatRoomList(query, option) {
    let list = await this.ctx.model.ChatRoom.find(
      query,
      [],
      option
    ).lean();

    if (!list || list.length === 0) {
      return [];
    }

    list = await Promise.all(
      list.map(async (item) => {
        const expertQuery = { user_id: item.to_user_id };
        const expert = await this.ctx.model.Expert.findOne(expertQuery,['name', 'avatar_image']).lean();

        if (expert && expert.name) {
          item.expert = {
            name: expert.name,
            avatar_image: expert.avatar_image,
          }
        }

        const messageQuery = {
          chat_room_id: item._id,
        };

        const messageOption = {
          skip: 0,
          limit: 1,
          sort: '-create_at',
        };

        const message = await this.ctx.model.ChatMessage.find(messageQuery, [], messageOption).exec();
        if (message && message.length !== 0) {
          for (var i = 0; i < message.length; i++) {
            item.update_at = dayjs(message[i].update_at).format('MM-DD');
          }
          item.message = message;
        }

        const osQuery = { chat_room_id: item._id };

        const os = await this.ctx.model.OrderSubscription.findOne(osQuery);
        if (os) {
          item.order = {
            orderId: os.order_id,
          }
        }
        return item;
      })
    )

    return [ list ];
  }

  async getChatRoom({ roomId }) {
    const ctx = this.ctx;
    const query = {
      '_id': roomId,
    };

    const room = await ctx.model.ChatRoom.findOne(query).exec();
    
    const fromUserData = await ctx.model.User.findOne({ _id: room.from_user_id }).exec();
    
    const toUserData = await ctx.model.User.findOne({ _id: room.to_user_id }). exec()

    if (!room) {
      return [];
    }

    return [ room, fromUserData ];
  }

  async getMessageList({ roomId }) {
    const ctx = this.ctx;
    const query = {
      'chat_room_id': roomId
    };

    const list = await ctx.model.ChatMessage.find(query, [], {}).lean();

    if (!list || list.length === 0) {
      return [ ];
    }

    return [ list ];
  }

  async incChatRommFromCount({ fromUserId, chatRoomId }) {
    const ctx = this.ctx;
    const query = { _id: chatRoomId };
    const room = await ctx.model.ChatRoom.findOne(query);
    let colse = false;

    if (room.close) {
      return [ true ];
    }

    if (room && room.from_user_id.toString() === fromUserId) {
      await ctx.model.ChatRoom.update(query, { $inc: { from_count: 1} });
    }
    // 发送消息超过17次结束对话
    if (room && room.from_user_id.toString() === fromUserId
    && room.from_count + 1 >= 3) {
      await ctx.model.ChatRoom.update(query, { close: true });
      colse = true;

      // 获取orderId
      const [ os ] = await ctx.service.order.getSubscriptionOrderDetailByQuery({
        chat_room_id: chatRoomId,
        user_id: fromUserId,
      });

      // 结束订单
      await ctx.service.payment.postPaymentDone({
        userId: fromUserId,
        orderId: os.order_id,
      });
    }
    return [ colse ];
  }

  newChatRoom({ fromUserId, toUserId }) {
    const ctx = this.ctx;
    const m = new ctx.model.ChatRoom();
    m.to_user_id = toUserId;
    m.from_user_id = fromUserId;
    m.state = 'OPEN';
    
    m.from_count = 0;
    m.to_count = 0;

    m.save();
    return m._id
  }

  newChatMessage(toUserData, fromUserData, message, roomId) {
    const ctx = this.ctx;
    const m = new ctx.model.ChatMessage();
    m.from_user_id = fromUserData._id;
    m.to_user_id = toUserData._id;
    m.chat_room_id = roomId;
    m.message = message;
    m.state = 'SEND';
    m.save();
    return m._id;
  }
}

module.exports = ChatService;
